package com.maimao.user.service.sys;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.maimao.core.exception.MaiMaoDaoException;
import com.maimao.core.model.resp.PageResult;
import com.maimao.user.mapper.sys.RoleMapper;
import com.maimao.model.user.sys.Role;
import com.maimao.model.user.sys.dto.DelDto;
import com.maimao.model.user.sys.dto.RoleSearchInput;
import com.maimao.model.user.sys.vo.RoleEx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author MaoLin Wang
 * @date 2020/12/6 4:35 下午
 */
@Service
public class RoleService {

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 分页条件查询
     *
     * @param page  当前页
     * @param size  页大小
     * @param input 条件参数
     * @return
     */
    public PageResult<RoleEx> search(Integer page, Integer size, RoleSearchInput input) {
        PageHelper.startPage(page, size);
        List<RoleEx> roles = roleMapper.selectByParams(input.getStatus(), input.getKey(), input.getSysRole());
        return new PageResult<>(roles);
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void addRole(RoleEx roleEx) {
        Role role = roleEx2Role(roleEx);
        roleMapper.insert(role);
        roleMapper.addRoleResourceRecord(role.getId(), roleEx.getResourceIds());
    }

    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void update(RoleEx roleEx) {
        Role role = roleEx2Role(roleEx);
        int i = roleMapper.updateById(role);
        if (i > 0) {
            roleMapper.deleteRecordBatch(role.getId());
            roleMapper.addRoleResourceRecord(role.getId(), roleEx.getResourceIds());
        }
    }

    private Role roleEx2Role(RoleEx roleEx) {
        return Role.builder()
                .id(roleEx.getId())
                .roleCode(roleEx.getRoleCode())
                .roleName(roleEx.getRoleName())
                .desc(roleEx.getDesc())
                .status(roleEx.getStatus())
                .createUser(roleEx.getCreateUser())
                .createTime(roleEx.getCreateTime())
                .updateUser(roleEx.getUpdateUser())
                .updateTime(roleEx.getUpdateTime())
                .sysRole(roleEx.getSysRole())
                .build();
    }


    @Transactional(rollbackFor = MaiMaoDaoException.class)
    public void updateStatusBatch(DelDto delDto) {
        List<Integer> ids = delDto.getIds();
        Integer status = delDto.getStatus();
        //没更新操作人
        roleMapper.updateStatusBatch(ids, status);
    }

    public List<Role> list() {

        List<Role> roles = roleMapper.selectLisAlltCus();
        return roles;
    }
}
